//
//  ChatViewModel.swift
//  WeChatClient
//
//  Created by AI Assistant on 2025/10/31.
//

import Foundation
import SwiftUI
import Combine

class ChatViewModel: ObservableObject {
    @Published var conversations: [Conversation] = []
    @Published var currentConversation: Conversation?
    @Published var newMessageText: String = ""
    @Published var showEmojiPicker: Bool = false
    @Published var showImagePicker: Bool = false
    
    private let mockDataService = MockDataService.shared
    
    init() {
        loadConversations()
    }
    
    func loadConversations() {
        conversations = mockDataService.getMockConversations()
    }
    
    func selectConversation(_ conversation: Conversation) {
        if let index = conversations.firstIndex(where: { $0.id == conversation.id }) {
            conversations[index].markAsRead()
            currentConversation = conversations[index]
        }
    }
    
    func sendMessage() {
        guard !newMessageText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
              let conversation = currentConversation else { return }
        
        let message = ChatMessage(
            content: newMessageText,
            type: .text,
            senderId: User.currentUser.userName,
            senderName: User.currentUser.displayName
        )
        
        if let index = conversations.firstIndex(where: { $0.id == conversation.id }) {
            conversations[index].addMessage(message)
            currentConversation = conversations[index]
            
            // 模拟对方回复
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                self.simulateReply()
            }
        }
        
        newMessageText = ""
    }
    
    func sendEmoji(_ emoji: String) {
        guard let conversation = currentConversation else { return }
        
        let message = ChatMessage(
            content: emoji,
            type: .emoji,
            senderId: User.currentUser.userName,
            senderName: User.currentUser.displayName
        )
        
        if let index = conversations.firstIndex(where: { $0.id == conversation.id }) {
            conversations[index].addMessage(message)
            currentConversation = conversations[index]
        }
        
        showEmojiPicker = false
    }
    
    func sendImage(_ imageName: String) {
        guard let conversation = currentConversation else { return }
        
        let message = ChatMessage(
            content: imageName,
            type: .image,
            senderId: User.currentUser.userName,
            senderName: User.currentUser.displayName
        )
        
        if let index = conversations.firstIndex(where: { $0.id == conversation.id }) {
            conversations[index].addMessage(message)
            currentConversation = conversations[index]
        }
        
        showImagePicker = false
    }
    
    private func simulateReply() {
        guard let conversation = currentConversation else { return }
        
        let replies = [
            "好的👌",
            "收到",
            "哈哈😄",
            "明白了",
            "👍",
            "没问题",
            "好的，谢谢",
            "😊"
        ]
        
        let randomReply = replies.randomElement() ?? "好的"
        let replyMessage = ChatMessage(
            content: randomReply,
            type: randomReply.count == 1 && randomReply.unicodeScalars.allSatisfy({ $0.properties.isEmoji }) ? .emoji : .text,
            senderId: conversation.participant.userName,
            senderName: conversation.participant.displayName
        )
        
        if let index = conversations.firstIndex(where: { $0.id == conversation.id }) {
            conversations[index].addMessage(replyMessage)
            currentConversation = conversations[index]
        }
    }
    
    var totalUnreadCount: Int {
        return conversations.reduce(0) { result, conversation in
            result + conversation.unreadCount
        }
    }
    
    func getEmojiCategories() -> [String: [String]] {
        return mockDataService.getEmojiCategories()
    }
}
